package org.example.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.example.admin.common.convention.exception.ClientException;
import org.example.admin.common.convention.exception.ServiceException;
import org.example.admin.dao.entity.UserDO;
import org.example.admin.dao.mapper.UserMapper;
import org.example.admin.dto.req.UserLoginReqDTO;
import org.example.admin.dto.req.UserRegisterReqDTO;
import org.example.admin.dto.req.UserUpdateReqDTO;
import org.example.admin.dto.resp.UserLoginRespDTO;
import org.example.admin.dto.resp.UserRespDTO;
import org.example.admin.service.GroupService;
import org.example.admin.service.UserService;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static org.example.admin.common.constant.RedisCacheConstant.LOCK_USER_LOGIN;
import static org.example.admin.common.constant.RedisCacheConstant.LOCK_USER_REGISTER;
import static org.example.admin.common.enums.errorEnum.UserErrorCodeEnum.*;

/**
 * @author weibin
 * @since 2025/10/3 19:29
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {

    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;
    private final RedissonClient redissonClient;
    private final StringRedisTemplate stringRedisTemplate;
    private final GroupService groupService;

    @Override
    public UserRespDTO getUserByUsername(String username) {
        LambdaQueryWrapper<UserDO> queryWrapper = new LambdaQueryWrapper<UserDO>()
                .eq(UserDO::getUsername, username);
        UserDO userDO = baseMapper.selectOne(queryWrapper);

        UserRespDTO userRespDTO = new UserRespDTO();
        BeanUtil.copyProperties(userDO, userRespDTO);

        return userRespDTO;
    }

    @Override
    public Boolean hasUsername(String username) {
        return userRegisterCachePenetrationBloomFilter.contains(username);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void register(UserRegisterReqDTO requestParam) {
        // 检查用户名是否已存在
        if (userRegisterCachePenetrationBloomFilter.contains(requestParam.getUsername())) {
            throw new ClientException(USER_NAME_EXIST);
        }

        // 使用分布式锁相同用户名高并发注册
        RLock lock = redissonClient.getLock(LOCK_USER_REGISTER + requestParam.getUsername());
        try {
            if (lock.tryLock()) {
                UserDO userDO = BeanUtil.copyProperties(requestParam, UserDO.class);
                // 兜底策略，数据库唯一索引保证用户名不重复
                try {
                    baseMapper.insert(userDO);
                } catch (DuplicateKeyException e) {
                    throw new ServiceException(USER_NAME_EXIST);
                }

                // 注册用户时创建一个默认分组
                groupService.saveGroup(requestParam.getUsername(), "默认分组");

                // 向布隆过滤器写入该用户
                userRegisterCachePenetrationBloomFilter.add(requestParam.getUsername());
                return;
            }
            throw new ClientException(USER_NAME_EXIST);
            // 获取不到锁那就直接返回用户名已存在，因为这是说明其他线程已获取到锁了
        } finally {
            // 最后一定得是否锁
            lock.unlock();
        }
    }

    @Override
    public void updateUser(UserUpdateReqDTO requestParam) {
        // TODO:判断当前修改的用户是否是当前登录用户，网管那一步在做
        LambdaUpdateWrapper<UserDO> updateWrapper = Wrappers.lambdaUpdate(UserDO.class)
                .eq(UserDO::getUsername, requestParam.getUsername());
        baseMapper.update(BeanUtil.toBean(requestParam, UserDO.class), updateWrapper);

    }

    @Override
    public UserLoginRespDTO login(UserLoginReqDTO requestParam) {
        // 检查用户是否存在
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, requestParam.getUsername())
                .eq(UserDO::getPassword, requestParam.getPassword())
                .eq(UserDO::getDelFlag, 0);
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        if (userDO == null) {
            throw new ClientException(USER_NULL);
        }

        // 生成一个用户唯一标识，存储到redis里，构建一个k-v关系，key:用户标识，value:用户基本消息，设置过期时间
        // 一级key
        String userLoginKey = LOCK_USER_LOGIN + requestParam.getUsername();
        // 二级key
        String uuid = UUID.randomUUID().toString();
        // 内部值
        String userInfo = JSON.toJSONString(userDO);

        // 判断用户是否已登录
        if (stringRedisTemplate.opsForHash().hasKey(userLoginKey, uuid)) {
            throw new ClientException(USER_LOGIN_HAS_LOGIN);
        }

        // 存入redis
        stringRedisTemplate.opsForHash().put(userLoginKey, uuid, userInfo);
        stringRedisTemplate.expire(userLoginKey, 30L, TimeUnit.DAYS);

        // 返回用户标识
        return new UserLoginRespDTO(uuid);

    }

    @Override
    public Boolean checkLogin(String username, String token) {
        return stringRedisTemplate.opsForHash().get(LOCK_USER_LOGIN + username, token) != null;
    }

    @Override
    public void logout(String username, String token) {
        if (checkLogin(username, token)) {
            stringRedisTemplate.delete(LOCK_USER_LOGIN + username);
            return;
        }
        throw new ClientException(USER_LOGIN_NOT_LOGIN);
    }
}
